#include "connexion.h"

int createSocket() {
	int sck; /* descripteur */
	SYS(sck=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)); /* creation d'un socket */
	return sck;
}

struct hostent * initHost(char * hostName) {
	struct hostent * host;
	host = gethostbyname(hostName);
	if (host == NULL) {
		printf("Ne trouve pas d'hôte \n");
		exit(1);
	}
	return host;
}

struct sockaddr_in * initClientAddress(int port, struct hostent * host) {
	struct sockaddr_in * serv_addr = (struct sockaddr_in*) malloc(
			sizeof(struct sockaddr_in));
	bzero((char*) serv_addr, sizeof(struct sockaddr_in));
	serv_addr->sin_family = AF_INET;
	serv_addr->sin_port = htons(port); /* host to network short */

	/* Copie de l'adresse du serveur dans la structure sockaddr_in */
	bcopy(host->h_addr, (char*) &(serv_addr->sin_addr.s_addr), host->h_length);
	return serv_addr;
}

void startConnection(int scket, struct sockaddr_in * address) {
	if (connect(scket, (struct sockaddr *) address, sizeof(struct sockaddr_in))
			< 0) {
		printf("Echec de la tentative de connexion\n");
		SYS(close(scket));
		exit(1);
	}
}

int verifierNumPort(char * chaine) {
	char *ptr;
	int val;
	val = strtol(chaine, &ptr, 10);
	if (*ptr != '\0')
		return -1;
	return 0;
}
